package game.scene.map.event;
import dgo.IO;
import dgo.tilemap.MapCharacter;
import game.scene.map.Model;

import java.util.Hashtable;
import java.util.Vector;
import org.json.me.JSONArray;
import org.json.me.JSONObject;

public class EventLoader {
  public static void loadEvents(Vector events, Model model, String eventID){

    String data = IO.readTextFile(model.getClass(), "/data/event/" + eventID + ".json");
    JSONArray tj = null;
    JSONArray arr = null;
    
    try{
      arr = (new JSONArray(data));
      for(int i = 0; i < arr.length(); i++){
        JSONObject eventData = arr.getJSONObject(i);
        
        tj = eventData.getJSONArray("pos");

        MapCharacter t = model.addCharacter(eventData.getInt("id"), Integer.parseInt(tj.getString(0)), Integer.parseInt(tj.getString(1)));

        int id = eventData.getInt("id");
        Event event = new Event(id, model, model.getCharacter(eventData.getInt("id")));
        JSONArray pages = eventData.getJSONArray("pages");
        
        JSONObject page, status, options;
        for(int pageNo = 0; pageNo < pages.length(); pageNo++){
          page = pages.getJSONObject(pageNo);
          status = page.getJSONObject("status");
          options = page.getJSONObject("options");
          
          EventParameters ep = new EventParameters(
            status.getString("chip_id"),
            (byte)status.getInt("hit_x"),
            (byte)status.getInt("hit_y"),
            (byte)status.getInt("off_x"),
            (byte) status.getInt("off_y"),
            (byte) status.getInt("dir"), 
            (byte)status.getInt("frame_no"), 
            status.getInt("alpha"), 
            (byte)status.getInt("wait"), 
            (byte)status.getInt("speed"), 
            status.getBoolean("route_repeat"), 
            status.getBoolean("route_skip"), 
            (byte)status.getInt("layer"), 
            options.getBoolean("dir_fix"), 
            options.getBoolean("move_anime"), 
            options.getBoolean("stay_anime"), 
            options.getBoolean("pass_tile"),
            options.getBoolean("pass_character"),
            options.getBoolean("pass_event"),
            false
          );
          event.push(new EventPage(event, model, page.getJSONArray("triggers"), page.getJSONArray("conditions"), page.getJSONArray("commands"), page.getJSONArray("route"), ep));
        }
        
        events.addElement(event);
      }
    } catch (org.json.me.JSONException e) {
      System.out.println("Couldn't get JSONArray for events: " + e);
    }
  }
}
